<script setup lang="ts">
// 监听键盘按键，直到回车结束
import {onMounted, onUnmounted, ref} from "vue";
import CryptoJS from 'crypto-js'
import {useRouter} from "vue-router";

const router = useRouter()
const inputStr = ref("")
const passwdStr = ref("")
/**
 * 页面加载时，初始化数据
 */
onMounted(() => {
  /**
   * 监听键盘按键
   * 并且一个页面只能有一个监听
   */
  console.log("onMounted")
  window.addEventListener('keyup', onKeyUp, { passive: true})
  inputStr.value = ""
  passwdStr.value = ""
})
/**
 * 监听键盘按键
 * @param e
 */
const onKeyUp = (e: KeyboardEvent) => {
  if (e.key === 'Enter') {
    passwdStr.value = inputStr.value
    passwdStr.value = CryptoJS.MD5(passwdStr.value).toString()
    console.log(passwdStr.value)
    if(passwdStr.value === '76a2173be6393254e72ffa4d6df1030a'){
      router.replace({
        name: 'mainView'
      })
    }
    inputStr.value = ""
  } else{
    inputStr.value += filterKey(e.key)
  }
}

/**
 * 过滤掉字母、数字、特殊字符之外的其他按键
 * 如果是其他按键，返回空字符串，否则返回输入的字符串
 * @return
 */
const filterKey = (key:string) =>{
  const ignoreKeys = ['Shift', 'Control', 'Alt', 'Meta', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Tab', 'CapsLock', 'Escape', 'Backspace', 'Delete', 'Enter', ' ',  'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12',  'Pause', 'ScrollLock', 'PrintScreen', 'Insert', 'Home', 'End', 'PageUp', 'PageDown', 'NumLock', ' ', ]
  if (!ignoreKeys.includes(key)) {
    return key
  }
  return ""
}

/**
 * 在组件销毁时，取消监听
 */
onUnmounted(() => {
  console.log("onUnmounted")
  window.removeEventListener('keyup', onKeyUp)
})
</script>

<template>
<div class="main-content">
  <span>请输入密码</span>
  <span>{{inputStr}}</span>
</div>
</template>

<style scoped>
.main-content{
  height: 100vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>